package info.nixbear.tgcms.admin.client.view;

import info.nixbear.tgcms.admin.shared.request.TemplateProxy;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.ui.client.ValueBoxEditorDecorator;
import com.google.gwt.text.shared.Renderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ValueListBox;
import com.google.gwt.user.client.ui.Widget;

public class TemplateEditor extends Composite implements Editor<TemplateProxy> {

	private static TemplateEditorUiBinder uiBinder = GWT
			.create(TemplateEditorUiBinder.class);

	interface TemplateEditorUiBinder extends UiBinder<Widget, TemplateEditor> {
	}

	public TemplateEditor() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@UiField ValueBoxEditorDecorator<String> name;
	@UiField ValueBoxEditorDecorator<String> contentType;
	@UiField ValueBoxEditorDecorator<String> htmlAsString;
	
	
	public static class TemplateValueListBoxRenderer implements Renderer<Long> {
		Map<Long, TemplateProxy> templatesMap;

		@Override
		public String render(Long key) {
			return (key == null) ? "null" : (templatesMap == null) ? "null"
					: (templatesMap.get(key) == null) ? "null" : templatesMap
							.get(key).getName();
		}

		@Override
		public void render(Long object, Appendable appendable)
				throws IOException {
			appendable.append(this.render(object));
		}

		public void setTemplates(Map<Long, TemplateProxy> templatesMap) {
			this.templatesMap = templatesMap;
		}
	}

	TemplateValueListBoxRenderer templateValueListBoxRenderer = new TemplateValueListBoxRenderer();

	@UiField(provided = true)
	ValueListBox<Long> parentTemplateId = new ValueListBox<Long>(
			templateValueListBoxRenderer);


	
	
	public void setTemplates(Collection<TemplateProxy> newValues) {
		Map<Long, TemplateProxy> templatesMap = new HashMap<Long, TemplateProxy>(
				newValues.size());
		for (TemplateProxy templateProxy : newValues) {
			templatesMap.put(templateProxy.getId(), templateProxy);
		}
		this.templateValueListBoxRenderer.setTemplates(templatesMap);
		templatesMap.put(new Long(0), null);
		this.parentTemplateId.setAcceptableValues(templatesMap.keySet());
	}

	
}
